<template>
  <el-upload
    :action="url"
    list-type="picture-card"
    accept="image/*"
    :data="basedata"
    :limit="limit"
    :multiple="true"
    :auto-upload="true"
    :show-file-list="false"
    :on-success="handleSuccess"
    :on-remove="handleRemove"
    :before-upload="handleUpload"
    :on-exceed="handleExceed"
    ref="uploadFile"
  >
  </el-upload>
</template>
<script setup name="upload">
import { post662092c66ee3c } from "@/utils/api.js";
import { get } from "@vueuse/shared";
import { ref, reactive, onMounted, inject } from "vue";
const injectMessage = inject("$message");

const props = defineProps({
  limit: {
    type: Number,
    default: 1,
  },
  filelist: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

const emit = defineEmits(["getfile"]);
let filelistData = ref([]);
let dialogImageUrl = ref("");
let dialogVisible = ref(false);
let basedata = ref({});
let url = ref("");
onMounted(() => {
  filelistData.value = props.filelist.map((item) => {
    return { url: item };
  });
  getOSSkey();
});
let ossInfo = ref({});
let uploadFile = ref(null);
function getOSSkey() {
  post662092c66ee3c({}).then((res) => {
    // console.log(res);
    if (res.code == 1) {
      ossInfo.value = res.data;
    }
  });
}
function handleUpload(file) {
  //   console.log("开始上传：", file);
  url.value = ossInfo.value.host;
  let name = file.name;
  ossInfo.value.OSSAccessKeyId = ossInfo.value.accessKeyId;
  ossInfo.value.key = ossInfo.value.dir + name;
  basedata.value = ossInfo.value;
  //   var img = ossInfo.value.host + "/" + ossInfo.value.key;
  //   filelistData.value.push(img);
  //   console.log(filelistData.value)
}
function handleSuccess(response, file, fileList) {
  console.log(fileList);
  let arr = [];
  if (fileList.length > 0) {
    fileList.forEach((item) => {
      arr.push(ossInfo.value.host + '/' + ossInfo.value.dir + item.name);
    });
  }
  filelistData.value = arr;
  emit("getfile", filelistData.value);
  // console.log(uploadFile.value);
  // uploadFile.value.clearFiles();
}
function handleExceed(files, fileList) {
  injectMessage.error(`当前限制选择 ${props.limit} 个文件`);
}
function handleRemove() {
  console.log(uploadFile.value);
  // uploadFile.value.clearFiles();
  // console.log(filelistData.value);
  // console.log("删除文件：", file);
  // filelistData.value = fileList;
  // var f = filelistData.value.find((item) => item.indexOf(file.uid) != -1);
  // var i = filelistData.value.indexOf(f);
  // filelistData.value.splice(i, 1);
  // emit("getfile", filelistData.value);
}
function handlePictureCardPreview(file) {
  console.log("文件预览：", file);
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}
defineExpose({
  handleRemove
});
</script>